package com.mobile.util;

import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @ClassName : StringUtil.java
 * @Decription : 字符串相关方法
 * @Version : 2018/01/11  hlh  新建作成   1.0
 */
public class StringUtil {

	/**
     * 16进制字符串转为2进制字符串
     *
     * @param hexString
     * @return
     */
    public static String hexString2binaryString(String hexString) {
        if (hexString == null || hexString.length() % 2 != 0)
            return null;
        String bString = "", tmp;
        for (int i = 0; i < hexString.length(); i++) {
            tmp = "0000" + Integer.toBinaryString(Integer.parseInt(hexString.substring(i, i + 1), 16));
            bString += tmp.substring(tmp.length() - 4);
        }
        return bString;
    }

	/**
	 * 将以逗号分隔的字符串转换成字符串数组
	 * @param valStr
	 * @return String[]
	 */
	public static String[] StrList(String valStr){
	    int i = 0;
	    String TempStr = valStr;
	    String[] returnStr = new String[valStr.length() + 1 - TempStr.replace(",", "").length()];
	    valStr = valStr + ",";
	    while (valStr.indexOf(',') > 0)
	    {
	        returnStr[i] = valStr.substring(0, valStr.indexOf(','));
	        valStr = valStr.substring(valStr.indexOf(',')+1 , valStr.length());

	        i++;
	    }
	    return returnStr;
	}

	/**获取字符串编码
	 * @param str
	 * @return
	 */
	public static String getEncoding(String str) {
	       String encode = "GB2312";
	      try {
	          if (str.equals(new String(str.getBytes(encode), encode))) {
	               String s = encode;
	              return s;
	           }
	       } catch (Exception exception) {
	       }
	       encode = "ISO-8859-1";
	      try {
	          if (str.equals(new String(str.getBytes(encode), encode))) {
	               String s1 = encode;
	              return s1;
	           }
	       } catch (Exception exception1) {
	       }
	       encode = "UTF-8";
	      try {
	          if (str.equals(new String(str.getBytes(encode), encode))) {
	               String s2 = encode;
	              return s2;
	           }
	       } catch (Exception exception2) {
	       }
	       encode = "GBK";
	      try {
	          if (str.equals(new String(str.getBytes(encode), encode))) {
	               String s3 = encode;
	              return s3;
	           }
	       } catch (Exception exception3) {
	       }
	      return "";
	   }

	/**
	 * 随机生成六位数验证码
	 * @return
	 */
	public static int getRandomNum(){
		 Random r = new Random();
		 return r.nextInt(900000)+100000;//(Math.random()*(999999-100000)+100000)
	}

	/**
	 * 检测字符串是否不为空(null,"","null")
	 * @param s
	 * @return 不为空则返回true，否则返回false
	 */
	public static boolean notEmpty(String s){
		return s!=null && !"".equals(s.trim()) && !"null".equals(s);
	}

	/**
	 * 检测字符串是否为空(null,"","null")
	 * @param s
	 * @return 为空则返回true，不否则返回false
	 */
	public static boolean isEmpty(String s){
		return s==null || "".equals(s.trim()) || "null".equals(s);
	}
	/**
	 * 检查对象是否为空(null,"","null")
	 * @param obj
	 * @return 为空则返回true，不否则返回false
	 */
	public static boolean isEmpty(Object obj){
		return null == obj || "".equals(obj);
	}

	/**
	 * 检测集合是否为空(null,"")
	 * @param list 集合
	 * @return 为空则返回true，不否则返回false
	 */
	public static boolean isEmptyList(List<?> list){
		return null == list || list.size() < 1;
	}

	/**
	 * 检测集合是否为空(null,"")
	 * @param map 集合
	 * @return 为空则返回true，不否则返回false
	 */
	public static boolean isEmptyMap(Map<?,?> map){
		return null == map || map.size() < 1;
	}

	/**
	 * 字符串转换为字符串数组
	 * @param str 字符串
	 * @param splitRegex 分隔符
	 * @return
	 */
	public static String[] str2StrArray(String str,String splitRegex){
		if(isEmpty(str)){
			return null;
		}
		return str.split(splitRegex);
	}

	/**
	 * 用默认的分隔符(,)将字符串转换为字符串数组
	 * @param str	字符串
	 * @return
	 */
	public static String[] str2StrArray(String str){
		return str2StrArray(str,",\\s*");
	}

	/**
	 * 按照yyyy-MM-dd HH:mm:ss的格式，日期转字符串
	 * @param date
	 * @return yyyy-MM-dd HH:mm:ss
	 */
	public static String date2Str(Date date){
		return date2Str(date,"yyyy-MM-dd HH:mm:ss");
	}

	/**
	 * 按照yyyy-MM-dd HH:mm:ss的格式，字符串转日期
	 * @param date
	 * @return
	 */
	public static Date str2Date(String date){
		if(notEmpty(date)){
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			try {
				return sdf.parse(date);
			} catch (ParseException e) {
				e.printStackTrace();
			}
			return new Date();
		}else{
			return null;
		}
	}

	/**
	 * 按照参数format的格式，日期转字符串
	 * @param date
	 * @param format
	 * @return
	 */
	public static String date2Str(Date date,String format){
		if(date!=null){
			SimpleDateFormat sdf = new SimpleDateFormat(format);
			return sdf.format(date);
		}else{
			return "";
		}
	}

	/**
	 * 把时间根据时、分、秒转换为时间段
	 * @param StrDate
	 */
	public static String getTimes(String StrDate){
		String resultTimes = "";

		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	    Date now;

	    try {
	    	now = new Date();
	    	Date date=df.parse(StrDate);
	    	long times = now.getTime()-date.getTime();
	    	long day  =  times/(24*60*60*1000);
	    	long hour = (times/(60*60*1000)-day*24);
	    	long min  = ((times/(60*1000))-day*24*60-hour*60);
	    	long sec  = (times/1000-day*24*60*60-hour*60*60-min*60);

	    	StringBuffer sb = new StringBuffer();
	    	//sb.append("发表于：");
	    	if(hour>0 ){
	    		sb.append(hour+"小时前");
	    	} else if(min>0){
	    		sb.append(min+"分钟前");
	    	} else{
	    		sb.append(sec+"秒前");
	    	}

	    	resultTimes = sb.toString();
	    } catch (ParseException e) {
	    	e.printStackTrace();
	    }

	    return resultTimes;
	}

	/**
	 * 写txt里的单行内容
	 * @param fileP  文件路径
	 * @param content  写入的内容
	 */
	public static void writeFile(String fileP,String content){
		String filePath = String.valueOf(Thread.currentThread().getContextClassLoader().getResource(""))+"../../";	//项目路径
		filePath = (filePath.trim() + fileP.trim()).substring(6).trim();
		if(filePath.indexOf(":") != 1){
			filePath = File.separator + filePath;
		}
		try {
	        OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(filePath),"utf-8");
	        BufferedWriter writer=new BufferedWriter(write);
	        writer.write(content);
	        writer.close();


		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	  * 验证邮箱
	  * @param email
	  * @return
	  */
	 public static boolean checkEmail(String email){
	  boolean flag = false;
	  try{
	    String check = "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
	    Pattern regex = Pattern.compile(check);
	    Matcher matcher = regex.matcher(email);
	    flag = matcher.matches();
	   }catch(Exception e){
	    flag = false;
	   }
	  return flag;
	 }

	 /**
	  * 验证手机号码
	  * @param mobileNumber
	  * @return
	  */
	 public static boolean checkMobileNumber(String mobileNumber){
	  boolean flag = false;
	  try{
	    Pattern regex = Pattern.compile("^(((13[0-9])|(15([0-3]|[5-9]))|(18[0,5-9]))\\d{8})|(0\\d{2}-\\d{8})|(0\\d{3}-\\d{7})$");
	    Matcher matcher = regex.matcher(mobileNumber);
	    flag = matcher.matches();
	   }catch(Exception e){
	    flag = false;
	   }
	  return flag;
	 }

	/**
	 * 检测KEY是否正确
	 * @param paraname  传入参数
	 * @param FKEY		接收的 KEY
	 * @return 为空则返回true，不否则返回false
	 */
	public static boolean checkKey(String paraname, String FKEY){
		paraname = (null == paraname)? "":paraname;
		return MD5.md5(paraname+DateUtil.getDays()+",fh,").equals(FKEY);
	}

	/**
	 * 读取txt里的单行内容
	 * @param fileP  文件路径
	 */
	@SuppressWarnings("resource")
	public static String readTxtFile(String fileP) {
		try {

			String filePath = String.valueOf(Thread.currentThread().getContextClassLoader().getResource(""))+"../../";	//项目路径
			filePath = filePath.replaceAll("file:/", "");
			filePath = filePath.replaceAll("%20", " ");
			filePath = filePath.trim() + fileP.trim();
			if(filePath.indexOf(":") != 1){
				filePath = File.separator + filePath;
			}
			String encoding = "utf-8";
			File file = new File(filePath);
			if (file.isFile() && file.exists()) { 		// 判断文件是否存在
				BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding));
				String lineTxt = null;
				while ((lineTxt = in.readLine()) != null) {
					return lineTxt;
				}
				in.close();
			}else{
				System.out.println("找不到指定的文件,查看此路径是否正确:"+filePath);
			}
		} catch (Exception e) {
			System.out.println("读取文件内容出错");
		}
		return "";
	}
	/**
	 * 字符串比较（忽略大小写比较两个字符串）
	 * 		str1 or str2 任意为空，返回false
	 * @param str1
	 * @param str2
	 * @return
	 */
	public static boolean equalsIgnoreCase(String str1,String str2){
		if (null == str1) {
			return false;
		} else if (null == str2) {
			return false;
		} else {
			return str1.equalsIgnoreCase(str2);
		}
	}

	/**
	 * 将整数传入后，装换为固定长度的字符串，位数不够，左补零
	 *
	 * @param number 传入整数
	 * @param strLength 转换后字符串长度
	 * @return
	 */
	public static String addZeroForNum(int number, int strLength) {

		String str = number + "";

	    int strLen = str.length();
	    StringBuffer sb = null;

	     while (strLen < strLength) {
	           sb = new StringBuffer();
	           sb.append("0").append(str);// 左补0
	           str = sb.toString();
	           strLen = str.length();
	     }

	    return str;
	}

	/**
	 * 删除数组中的Null项
	 *
	 * @param strArray 数组对象
	 * @return 处理后数组对象
	 */
	public static String[] removeArrayEmptyTextBackNewArray(String[] strArray) {
        List<String> strList= Arrays.asList(strArray);
        List<String> strListNew=new ArrayList<>();
        for (int i = 0; i <strList.size(); i++) {
            if (strList.get(i)!=null&&!strList.get(i).equals("")){
                strListNew.add(strList.get(i));
            }
        }
        String[] strNewArray = strListNew.toArray(new String[strListNew.size()]);
        return   strNewArray;
    }

	/**
	 * 数组合并处理
	 * 多数组间，相同项不覆盖，不同项覆盖(用于多站点各监测指标统合显示)。
	 *
	 * @param argList 集合对象
	 * @return 处理后数组对象
	 */
	public static String[] integrationString (List<String> argList) {
		String[] itemStrArr = null;
		String[] itemStrArrAll = new String[20];
		for(int i = 0; i<argList.size();i++ ) {
			itemStrArr = argList.get(i).split(";");
			for(int j = 0; j<itemStrArr.length;j++ ) {
				if(!itemStrArr[j].equals(itemStrArrAll[j]) && !"".equals(itemStrArr[j])){
					Arrays.fill(itemStrArrAll, j,j+1,itemStrArr[j]);
				}

			}
		}
		//  删除数组中的Null项
		return removeArrayEmptyTextBackNewArray(itemStrArrAll);
	}

	/**
	 * 数组转Map处理
	 *
	 * @param array 数组对象
	 * @return 处理后数组对象
	 */
	public static Map<Object,Object> arrayToMap (String[] array) {
		Map<Object,Object> resultMap = new HashMap<Object,Object>();
		String[] itemStrArr = null;
		for(int i = 0; i<array.length;i++ ) {
			itemStrArr = array[i].split(":");
			if(!isEmpty(itemStrArr) && itemStrArr.length > 0) {
				resultMap.put(itemStrArr[0], itemStrArr[1]);
			}
		}
		// 删除数组中的Null项
		return resultMap;
	}

    /**
     * 字符串转化成为16进制字符串
     * @param s
	 *
     * @return
     */
    public static String strTo16(String s) {
        String str = "";
        for (int i = 0; i < s.length(); i++) {
            int ch = (int) s.charAt(i);
            String s4 = Integer.toHexString(ch);
            str = str + s4;
        }
        return str;
    }
    private static byte toByte(char c) {
        byte b = (byte) "0123456789abcdef".indexOf(c);
        return b;
    }
    /**
     * 16进制字符串转化为二进制数据
     * @param hex
     * @return
     */
	public static byte[] hexStringToByte(String hex) {
        int len = (hex.length() / 2);
        byte[] result = new byte[len];
        char[] achar = hex.toCharArray();
        for (int i = 0; i < len; i++) {
            int pos = i * 2;
            result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));
        }
        return result;
    }


    /**
     * 16进制转换成为string类型字符串
          *  转换前：32 30 31 39 31 31 32 30 30 30 30 30 30 30 31
     * @param s
     * @return
     */
    public static String hexStringToString(String s) {
        if (s == null || s.equals("")) {
            return null;
        }
        s = s.replace(" ", "");
        byte[] baKeyword = new byte[s.length() / 2];
        for (int i = 0; i < baKeyword.length; i++) {
            try {
                baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            s = new String(baKeyword, "UTF-8");
            //new String();
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return s;
    }

    /**
     * 16进制转换成为string类型字符串
          *  前方直接加0的所谓16进制数据转字符串
          *  如：08 06 09 09 07 06 00 03 06 02 06 06 07 07 04
     *  869976036266774
     * @param s
     * @return
     */
    public static String hexZeroToString(String s) {
    	String r = null;
        if (s == null || s.equals("")) {
            return r;
        }
        s = s.replace(" ", "");
        byte[] baKeyword = new byte[s.length() / 2];
        r = "";
        for (int i = 0; i < baKeyword.length; i++) {
            try {
                r = r + Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return r;
    }

    /**
     * 将字节数组转换成字符串类型，以指定字符分割。
     * @param bytes
     * @param separator
     * @return
     */
    public static String getHexString(byte[] bytes, String separator) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (bytes != null && bytes.length > 0) {
            for(int i = 0; i < bytes.length; ++i) {
                int v = bytes[i] & 255;
                String hv = Integer.toHexString(v);
                if (hv.length() < 2) {
                    stringBuilder.append(0);
                }

                stringBuilder.append(hv + separator);
            }
            return stringBuilder.toString();
        } else {
            return null;
        }
    }

    /**
     * 判断字符是否是16进制数据
     * @return true:是
     *   	   false:不是
     */
    public static boolean isHexValue(String value) {
    	String regex="^[A-Fa-f0-9]+$";
    	  if(value.matches(regex)){
    		  return true;
    	  }else{
    		  return false;
    	  }
    }
}
